package msb.jvm.classloader;

import msb.jvm.basic.T;

import java.io.*;

public class T06_MSBClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File f = new File("c:/test/", name.replace(".", "/").concat(".class"));
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            fis = new FileInputStream(f);
            baos = new ByteArrayOutputStream();
            int b = 0;

            while ((b = fis.read()) != 0) {
                baos.write(b);
            }

            byte[] bytes = baos.toByteArray();
            baos.close();
            fis.close();
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader c = new T06_MSBClassLoader();
        Class clazz1 = c.loadClass("msb.jvm.classloader.Test");
        Class clazz2 = c.loadClass("msb.jvm.classloader.Test");
        System.out.println(clazz1 == clazz2);

        Test o = (Test) clazz1.newInstance();

        System.out.println(c.getClass().getClassLoader());
        System.out.println(c.getParent());

    }
}
